package com.ktjiaoyu.crm.controller;

import com.ktjiaoyu.crm.config.shiro.MyShiroRealm;
import com.ktjiaoyu.crm.pojo.Right;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.UserService;
import com.ktjiaoyu.crm.utils.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Resource
    UserService userService;
    @Resource
    RightService rightService;
    @Resource
    StringRedisTemplate stringRedisTemplate;


    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/dologin")
    public String dologin(String usrName, String usrPassword,
                          boolean rememberMe,
                          HttpSession session, Model model){
//        usrPassword= MD5Util.encryptPassword(usrPassword);
//        User user = userService.login(usrName, usrPassword);
//        //判断数据库中是否存在
//        if(user!=null){//登录成功
//            //1.将登录用户保存到session
//            session.setAttribute("loginUser",user);
//            //2.跳转到首页
//            return "redirect:/main";
//        }else{//登录失败
//            //1.将错误信息存储到model
//            model.addAttribute("msg","用户名或者密码错误");
//            //2.跳转到登录页面
//            return "login";
//        }

        //4.获取subject
        Subject subject = SecurityUtils.getSubject();
//        UsernamePasswordToken token=
//                new UsernamePasswordToken(usrName,usrPassword);
        UsernamePasswordToken token=
                new UsernamePasswordToken(usrName,usrPassword,rememberMe);
        try {
            subject.login(token);
            User user=(User)subject.getPrincipal();

            //获取当前登录用户权限
            Role role = user.getRole();
            //获取当前登录用户的权限信息
            List<Right> rights = rightService.findRightsByRoleId(role.getRoleId());
            role.setRights(rights);

            Session session1 = subject.getSession();

            //1.将登录用户保存到session
            session.setAttribute("loginUser",user);

            System.out.println(session1==session);
            System.out.println(session1.getId());
            System.out.println(session.getId());

            //计数器删除
            stringRedisTemplate.delete("shiro_login_count_"+token.getUsername());

            //清空当前登录用户的权限缓存
            RealmSecurityManager realmManager= (RealmSecurityManager)SecurityUtils.getSecurityManager();
            MyShiroRealm realm=(MyShiroRealm)realmManager.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo();

            //2.跳转到首页
            return "redirect:/main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            //1.将错误信息存储到model
            model.addAttribute("msg","用户名或者密码错误");
            //2.跳转到登录页面
            return "login";
        }
    }

    @GetMapping("/main")
    public String main(){
        return "main";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");

        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return "login";
    }

    @GetMapping("/403")
    public String authorization(){
        return "403";
    }

}
